//
//  AssuranceableViewCell.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/18.
//

import UIKit
import WebKit

typealias BlockWebViewHeight = (_ webViewHeight: CGFloat) -> Void//web高度

class AssuranceableViewCell: UITableViewCell {
    var titleBtn: UIButton!
    var showImagView: UIImageView!
    var webView: WKWebView!
    var webViewHeight: CGFloat = 0.01
    
    var webViewHeightBlock: BlockWebViewHeight!//web高度
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?){
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = .white
        self.clipsToBounds = true
        self.selectionStyle = .none
        self.addInitSubview()
        self.addLayout()
        
    }
    
    func addInitSubview() {
     
        titleBtn = UIButton.init(frame: CGRect.zero)
        self.titleBtn.setTitle(MMLocalizedString("more_information", comment: "更多资料"), for: .normal)
        titleBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        titleBtn.setTitleColor(Theme.titleLabColor, for: .normal)
        titleBtn.setTitleColor(Theme.titleLabColor, for: .highlighted)
        titleBtn.semanticContentAttribute = .forceRightToLeft
        titleBtn.contentHorizontalAlignment = .left
        self.contentView.addSubview(titleBtn)
        
        
        let config = WKWebViewConfiguration.init()
        let userContentController = WKUserContentController()
        config.userContentController = userContentController
        self.webView = WKWebView.init(frame: CGRect(x: 38, y: self.titleBtn.bottom + 20, width: kScreenWidth - 72, height: 270))
        self.webView.uiDelegate = self
        self.webView.navigationDelegate = self
        self.webView.autoresizesSubviews = true
        self.webView.allowsBackForwardNavigationGestures = false
        self.webView.isUserInteractionEnabled = true
        self.webView.scrollView.isUserInteractionEnabled = true
        self.webView.sizeToFit()
        self.webView.scrollView.isScrollEnabled = false
        self.contentView.addSubview(self.webView)
        self.webView.scrollView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.new, context: nil)
      
    }
    
    func addLayout() {
        
        self.titleBtn.snp.makeConstraints{ make in
            make.top.equalTo(10)
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.height.equalTo(20)
        }
        
        self.webView.snp.makeConstraints{ make in
            make.top.equalTo(self.titleBtn.snp.bottom).offset(10)
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.height.equalTo(self.webViewHeight)
            make.bottom.equalTo(-20)
        }
        
    }
    
    //Model
    func setAssuranceableViewCell(htmlStr: String){
        if htmlStr != "" && self.webViewHeight < 20 {
            self.webView.loadHTMLString(XTManageCenter.getHtmlLocalScaleString(htmlStr: htmlStr), baseURL: nil)
        }
        self.updateConstraints()
    }
    
    
    ///监听进度条
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        ///监听webView.scrollview的大小
        if keyPath == "contentSize" {
            if self.webView.frame.size.height < self.webView.scrollView.contentSize.height {
                self.webViewHeight = self.webView.scrollView.contentSize.height
                self.webView.snp.updateConstraints { (make) in
                    make.height.equalTo(self.webViewHeight)
                }
                self.updateConstraints()
//                if self.webViewHeightBlock != nil {
//                    self.webViewHeightBlock(self.webViewHeight)
//                }
                if let table = self.superview as? UITableView {
                    table.beginUpdates()
                    self.webView.snp.updateConstraints { (make) in
                        make.height.equalTo(self.webViewHeight)
                    }
                    table.endUpdates()
                }
            }
        }
    }
    
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

extension AssuranceableViewCell:WKUIDelegate, WKNavigationDelegate {
    func webViewUserContentController(_ scriptMessageHandlerArray: [String], didReceive message: WKScriptMessage) {
        //
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        printLog("开始加载")
    }
    
    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!){
        print(webView.height)
    }
   
    
//    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
//        webView.scrollView.isScrollEnabled = false
//        webView.evaluateJavaScript("document.body.offsetHeight") { (result, error) in
//            if result == nil{
//             return
//            }
//            let documentheight = result as! CGFloat
//            webView.evaluateJavaScript("document.body.offsetWidth", completionHandler: { (result , error) in
//                let documentwidth = result as! CGFloat
//               let pre = documentwidth/documentheight as CGFloat
//               self.webView.frame.size.height = kScreenWidth/pre
//                if(self.webViewHeight < self.webView.frame.size.height) {
//                    self.webViewHeight = self.webView.frame.size.height
//                    self.webView.snp.updateConstraints { (make) in
//                        make.height.equalTo(self.webViewHeight)
//                    }
//                }
//                if self.webViewHeightBlock != nil {
//                    self.webViewHeightBlock(self.webViewHeight)
//                }
//            })
//        }
//    }

}


